package com.ywj.chatroom.room;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        //创建服务器端的Socket对象
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("------->服务器开启<--------");
        while(true){
            //设置阻塞，只有一个客户端连接时，accept才能返回数据对象（监听客户端连接
            Socket socket = serverSocket.accept();
            //获得服务端的IP和端口号
            String ip = socket.getInetAddress().getHostAddress();
            int port = socket.getPort();
            System.out.println("一个客户上线 ip   " + ip + ":" + port);
            //接收客户端,开启线程
            new Thread(() ->{
                try{
                    InputStream is = socket.getInputStream();
                    byte[] arr = new byte[1024];
                    int len;
                    while((len=is.read(arr))!=-1){
                        String msg = new String(arr, 0, len);
                        System.out.println(ip + " : " + msg);
                    }
                    is.close();
                    socket.close();
                } catch (IOException e) {
                    //e.printStackTrace();
                }
            }).start();
        }
    }
}
